<?php

namespace App\Admin\Models;

use App\Admin\Models\BaseModel;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\MessageBag;
use Ixudra\Curl\Facades\Curl;
use Encore\Admin\Facades\Admin;
use App\Services\Common;
use DB;

class storeGoodsOut extends BaseModel
{
    //指定主键
    protected $primaryKey = 'sgiId';

    public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
    {
        $perPage = Request::get('per_page', 20);
        $page = Request::get('page', 1);

        $sgName = urlencode(Request::get('sgName', ''));
        $muNickName = urlencode(Request::get('muNickName', ''));

        $start = ($page-1)*$perPage;

		///////获取数据//////////////////////////////////////////////////////////////////////////////////////
		$sId = Admin::user()->sId;
		//$auCode = Admin::user()->auCode;

		$url = $this->host."/storeGoodsOut/getList?page={$page}&perPage={$perPage}&scKey={$sId}&sgName={$sgName}&muNickName={$muNickName}";
		$response = Curl::to($url)->get();
		$data = $this->handelApiData($response);

		////////获取数据/////////////////////////////////////////////////////////////////////////////////////

		$total = $data['count'];

        extract($data['data']);

        $tags = static::hydrate($data['data']);

        $paginator = new LengthAwarePaginator($tags, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }

    /**
     * Add a basic where clause to the query.
     *
     * @param  string|array|\Closure  $column
     * @param  mixed   $operator
     * @param  mixed   $value
     * @param  string  $boolean
     * @return $this
     */
    public function where($column, $operator = null, $value = null, $boolean = 'and'){
    	// http://localhost:96/admin/remark/remarkTag?rtcId=1
    	// $column rtcId
    	// $operator 1
    	// $value null
    	// $boolean and
    	return $this;
    }

	// 保存提交的form数据
	public function save(array $options = Array())
	{

	    $attributes = $this->getAttributes();

	    $userName = Admin::user()->name;
	    $now = date('Y-m-d H:i:s', time());

		$ignore = ['createUser', 'createTime', 'updateUser', 'updateTime'];
		$newAttributes = array();
		foreach($attributes as $key => $value){
			if (!in_array($key, $ignore)){
				$newAttributes[$key] = $value;
			}
		}

		$accountPay = 0;
		if ($_POST['accountMoney'] >= $attributes['sgoSalePrice']){
			$payMoney = 0;
			$newAttributes['sgoPayWay'] = "会员卡";
			$accountPay = $attributes['sgoSalePrice'];
		} else if ($_POST['accountMoney'] > 0){
			$payMoney = $attributes['sgoSalePrice'] - $_POST['accountMoney'];
			$newAttributes['sgoPayWay'] = "会员卡({$_POST['accountMoney']})/".$newAttributes['sgoPayWay']."({$payMoney})";
			$accountPay = $_POST['accountMoney'];
		} else {
			$payMoney = $attributes['sgoSalePrice'];
		}

		$auId = Admin::user()->auCode;
		$sId = Admin::user()->sId;

		$Common = new Common();
		// 记录支付金额
		if ($payMoney > 0){
			$payType = '';
			if ($newAttributes['sgoPayWay'] == '现金'){
				$payType = 'incomeCash';
			} else if ($newAttributes['sgoPayWay'] == '支付宝') {
				$payType = 'incomeAlipay';
			} else if ($newAttributes['sgoPayWay'] == '微信') {
				$payType = 'incomeWx';
			}
			$sInfo = DB::table('store')->where("sId", $sId)->first();
			$Common->addStats($sId, $payType, $payMoney, $sInfo->sCode);
		}

		$result = $Common->sellGoods($sId, $auId, $newAttributes['sgId'],
									$newAttributes['sgoSaleNum'], $newAttributes['sgoSalePrice'],
									$newAttributes['sgoMemo'], $userName, $newAttributes['muId'],
									$newAttributes['sgoPayWay'], $newAttributes['customUnitPriceSwich'],
									$accountPay);

		if ($result !== true){
			$error = new MessageBag([
		        'title'   => '保存失败',
		        'message' => $result,
		    ]);

		    return back()->with(compact('error'))->withInput();
		}

		// 减少卡内余额 //////////////////////////////////////////
		$host = config('admin.dataApiHost');
		$walletUrl = $host."/wallet/addTrade";
		$walletData = array();
		$walletData['wcusKey'] = $sId;
		$walletData['wtObj'] = 'goods';
		$walletData['wtObjId'] = $newAttributes['sgId'];
		$walletData['createUser'] = $userName;
		$walletData['uId'] = $newAttributes['muId'];
		if ($_POST['accountMoney'] >= $attributes['sgoSalePrice']){
			$walletData['wtChangedMoney'] = -1*$attributes['sgoSalePrice'];
		} else if ($_POST['accountMoney'] > 0){
			$walletData['wtChangedMoney'] = -1*$_POST['accountMoney'];
		}
		$walletData['wtAbstract'] = '购买消费';
        $rst = Curl::to($walletUrl)->withData($walletData)->post();
        $rst = json_decode($rst, true);
        if($rst['code'] == 1){// 添加日记录
            $store = DB::table('store')->where('sId', $sId)->first();
            if($store){
                $day['scKey'] = $sId;
                $day['sdObjId'] = $store->sCode;
                $day['sdName'] = 'consumption';
                $day['sdValue'] = abs($walletData['wtChangedMoney']);
                $url = $this->host."/statistics/dayAdd";
                $rst = Curl::to($url)->withData($day)->post();
//                var_dump($day);var_dump($url);exit;
            }

        }
		// 减少卡内余额 //////////////////////////////////////////

		return $this;
	}


	public function getStoreGoodsList(){

		$sId = Admin::user()->sId;
		$url = $this->host."/storeGoods/getList?scKey={$sId}&page=1&perPage=1000";
    	$response = Curl::to($url)->get();
    	$data = $this->handelApiData($response);
    	$selectArray = array();
    	foreach ($data['data'] as $pInfo){
    		$selectArray[$pInfo['sgId']] = $pInfo['sgName'];
    	}

    	return $selectArray;
	}

	public function getDistribution(){
		$attributes = $this->getAttributes();
		$dpId = $this->getProduct($attributes['sgId']);
		$sId = Admin::user()->sId;
		$uid = Admin::user()->id;
		$dlId = Admin::user()->dlId; //返利等级
		$createUser = Admin::user()->name; //操作人姓名
		$url = $this->host."/distributionUsers/distribution";
		$attributes['dcKey'] = $sId;
		$attributes['uId'] = $uid;
		$attributes['dpId'] = $dpId['dpId'];
		$attributes['dbMemo'] = $attributes['sgoMemo'];
		$attributes['money'] = $attributes['sgoSalePrice']; //销售金额
		$attributes['operationUser'] = $createUser;
		$ignore = ['sgoSaleNum', 'sgoSalePrice', 'sgoMemo'];
		$newAttributes = array();
		foreach($attributes as $key => $value){
			if (!in_array($key, $ignore)){
				$newAttributes[$key] = $value;
			}
		}
		$response = Curl::to($url)
					->withData($newAttributes)
					->post();

    	$data = json_decode($response, true);

		if (!isset($data['code'])){
			$error = new MessageBag([
		        'title'   => '系统错误',
		        'message' => '',
		    ]);

		    return back()->with(compact('error'));
		}
		if ($data['code'] == 0){

			    $error = new MessageBag([
			        'title'   => '保存失败',
			        'message' => $data['msg'],
			    ]);

			    return back()->with(compact('error'));

		}else{

				if(isset($data['data']['dbSelfMoney']) && $data['data']['dbSelfMoney'] > 0){
					$this->getwallet($uid,$sId,$data['data']['dbSelfMoney'],$createUser);  //店员流水记录
				}
				if(isset($data['data']['duParentUid'])){
					$this->getwallet($data['data']['duParentUid'],$sId,$data['data']['dbParentMoney'],$createUser);  //上级流水记录
				}
				if(isset($data['data']['duGrandUid'])){
					$this->getwallet($data['data']['duGrandUid'],$sId,$data['data']['dbGrandMoney'],$createUser);  //上上级流水记录
				}

			    $success = new MessageBag([
			        'title'   => '保存成功',
			        'message' => $data['msg'],
			    ]);

			    return back()->with(compact('success'));
		}
    	return $this;

	}

	public function getProduct($id){
		$sId = Admin::user()->sId;
		$url = $this->host."/storeGoods/get/{$id}?mcKey=".$sId;
		$response = Curl::to($url)->get();
		$data = $this->handelApiData($response);
		$data = json_decode($response, true);
		return $data['data'];
	}

	public function getwallet($uid,$sId,$money,$createUser,$wtOrderCode=null,$wtCost=null,$wtProfit=null,$wtAbstract=null){
		$attributes = array();
		$url = $this->host."/wallet/addTrade";
		$attributes['wcusKey'] = $sId;
		$attributes['uId'] = $uid;
		$attributes['wtChangedMoney'] = $money; //流水金额
		$attributes['wtOrderCode'] = $wtOrderCode; //流水号
		$attributes['wtCost'] = $wtCost; //成本
		$attributes['wtProfit'] = $wtProfit; //利润
		$attributes['wtAbstract'] = $wtAbstract; //摘要
		$attributes['createUser'] = $createUser;
		$response = Curl::to($url)
					->withData($attributes)
					->post();

    	$data = json_decode($response, true);

		if (!isset($data['code'])){
			$error = new MessageBag([
		        'title'   => '系统错误',
		        'message' => $data,
		    ]);

		    return back()->with(compact('error'));
		}
		if ($data['code'] == 0){

			    $error = new MessageBag([
			        'title'   => '保存失败',
			        'message' => $data['msg'],
			    ]);

			    return back()->with(compact('error'));

		}else{

			    $success = new MessageBag([
			        'title'   => '保存成功',
			        'message' => $data['msg'],
			    ]);

			    return back()->with(compact('success'));
		}
		return $this;
	}

	// 执行分销
	private function toDistribution($buyUserId, $sellUserId, $goodsId, $goodsNum, $money, $sgoCost, $goodsName){

		$distributionInfo = $this->getUserDistribution($sellUserId);

		$parentId = $distributionInfo['duParentUid'];
		$grandId = $distributionInfo['duGrandUid'];

		$countData = array();
		$sId = Admin::user()->sId;
		$countData['goodsId'] = $goodsId;
		$countData['acKey'] = $sId;
		$countData['goodsNum'] = $goodsNum;
		$countData['payMoney'] = $money;

		$buyUserInfo = $this->getUserInfoByUid($buyUserId);

		if (!$buyUserInfo){
			$countData['selfLevel'] = 1;
		}else{
			$countData['selfLevel'] = $buyUserInfo['alId'];
		}

		$countData['sellLevel'] = Admin::user()->alId;

		$Common = new Common();
		if ($parentId){
			$countData['parentLevel'] = $Common->getDistributionLevel($parentId);
			if ($grandId){
				$countData['grandLevel'] = $Common->getDistributionLevel($grandId);
			}
		}
//print_r($countData);exit;
		$host = config('admin.dataApiHost');
		$url = $host."/agencyGoodsPrice/countMoney";

		$data = Curl::to($url)->withData($countData)->get();

		try {
		    $data = json_decode($data, true);
		} catch (Exception $e) {
		    return $data;
		}

		if ($data['code'] == 0){
			return $data['msg'];
		}

		$info = $data['data'];

		if ($info['surplusMoney'] <= 0){
			return '系统错误，分销剩余不能小于0';
		}

		// 记录统计
		$statsUrl = $host."/statistics/dayAdd";
		$statsData = array();
		$statsData['scKey'] = $sId;

		$walletUrl = $host."/wallet/addTrade";
		$walletData = array();
		$walletData['wcusKey'] = $sId;
		$walletData['wtObj'] = 'goods';
		$walletData['wtObjId'] = $goodsId;
		$walletData['wtAbstract'] = '卖出商品提成';
		$walletData['createUser'] = Admin::user()->name;

		if ($info['sell'] > 0){
			$walletData['uId'] = $sellUserId;
			$walletData['wtChangedMoney'] = $info['sell'];

			$data = Curl::to($walletUrl)->withData($walletData)->post();
		}
		if ($info['parent'] > 0){
			$walletData['uId'] = $parentId;
			$walletData['wtChangedMoney'] = $info['parent'];
			$data = Curl::to($walletUrl)->withData($walletData)->post();
		}
		if ($info['grade'] > 0){
			$walletData['uId'] = $grandId;
			$walletData['wtChangedMoney'] = $info['grade'];
			$data = Curl::to($walletUrl)->withData($walletData)->post();
		}


		$storeInfo = $Common->getStroeInfo();
		$walletData['uId'] = $storeInfo['sCode'];
		$walletData['wtChangedMoney'] = $money;
		$walletData['wtCost'] = $money-$info['surplusMoney']+$sgoCost;
		$walletData['wtProfit'] = $info['surplusMoney']-$sgoCost;
		$walletData['wtAbstract'] = '卖出商品流水';

		$data = Curl::to($walletUrl)->withData($walletData)->post();

		/////////////////////////////////////////////////
		$sInfo = DB::table('store')->where("sId", $sId)->first();
		$statsData['sdObjId'] = $sInfo->sCode;
		$statsData['sdName'] = 'flowAccount';
		$statsData['sdValue'] = $money;
		Curl::to($statsUrl)->withData($statsData)->post();
		$statsData['sdName'] = 'cost';
		$statsData['sdValue'] = $walletData['wtCost'];
		Curl::to($statsUrl)->withData($statsData)->post();
		$statsData['sdName'] = 'profit';
		$statsData['sdValue'] = $walletData['wtProfit'];
		Curl::to($statsUrl)->withData($statsData)->post();
		/////////////////////////////////////////////////////

		// 记录分销日志
		$logUrl = $host."/distributionBill/add";
		$logData = array();
		$logData['dcKey'] = $sId;
		$logData['orderId'] = '';
		$logData['dbSaleMoney'] = $money;
		$logData['dbSelfMoney'] = $info['sell'];
		$logData['dbParentMoney'] = $info['parent'];
		$logData['dbGrandMoney'] = $info['grade'];
		$logData['dbSurplusMoney'] = $info['surplusMoney'];
		$logData['dbMemo'] = '';
		$logData['uId'] = $sellUserId;
		$logData['parentUid'] = $distributionInfo['duParentUid'];
		$logData['grandUid'] = $distributionInfo['duGrandUid'];
		$logData['dbObjName'] = $goodsName;
		$logData['dbObjId'] = $goodsId;
		$logData['createUser'] = Admin::user()->name;

		Curl::to($logUrl)->withData($logData)->post();

		return true;
	}

	// 获取分销关系
    private function getUserDistribution($userId){
    	$sId = Admin::user()->sId;
		$host = config('admin.dataApiHost');
		$url = $host."/distributionUsers/getUserInfo?dcKey={$sId}&uId={$userId}";

		$data = Curl::to($url)->get();

		$data = json_decode($data, true);
		$info = $data['data'];

		return $info;
    }

//  // 获取分销信息
//  private function getUserDistribution($userId){
//  	$sId = Admin::user()->sId;
//		$host = config('admin.dataApiHost');
//		$url = $host."/distributionUsers/getUserInfo?dcKey={$sId}&uId={$userId}";
//
//		$data = Curl::to($url)->get();
//
//		$data = json_decode($data, true);
//		$info = $data['data'];
//
//		return $info;
//  }

    // 获取用户信息
    private function getUserInfoByUid($userId){
    	$sId = Admin::user()->sId;
		$host = config('admin.dataApiHost');
		$url = $host."/member/getUserInfoByUserId?mcKey={$sId}&userId={$userId}";

		$data = Curl::to($url)->get();

		$data = json_decode($data, true);
		$info = $data['data'];

		return $info;
    }
}
